//
//  BeautyPictureVC.m
//  ErWa
//
//  Created by 赵颜彬 on 16/3/10.
//  Copyright © 2016年 www.lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "BeautyPictureVC.h"
#import "BeautyPictureCell.h"
#import "BeautyPictureModel.h"
#import <UIImageView+WebCache.h>
#import "AFNetworking.h"
#import "NewNestHeader.h"
@interface BeautyPictureVC ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic, strong) UICollectionView *collectionview;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, assign) NSInteger number;/**< 加载新数据时动态值 */
@property (nonatomic, assign) NSInteger tagid;/**< 加载新数据时动态值 */

@property (nonatomic, retain)UIScrollView *scrollView;
@property (nonatomic, retain)UIImageView *imageview;
@property (nonatomic, assign)CGRect originalFrame;
@property (nonatomic, assign)BOOL isDoubleTap;

@end

@implementation BeautyPictureVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"美图";//标题
    
    [self Handler];
    
    [self createSubviews];
    self.tagid = 7;
    self.number = 2;
    [self refresh];
    
    
    
}
#pragma mark - 刷新加载
- (void)refresh
{
    self.collectionview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(Handler)];
    [self.collectionview.mj_header beginRefreshing];
    
    
        
        self.collectionview.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    if (_dataArr.count !=0) {
        [self.collectionview.mj_footer beginRefreshing];
    }
}
#pragma mark - 加载数据
- (void)loadNewData{
     NSString *urlStr = [NSString stringWithFormat:@"http://appapi.17house.com/xiaoguotuApi.php?action=imageList&bid=6&page=%ld&pageSize=10&tagid=%ld", (long)self.number,(long)self.tagid];
    [AFNetworking GETWithURL:urlStr completion:^(id result) {
        // 创建新的数组用来保存新数据
        NSMutableArray *newDataArr = [NSMutableArray array];
        newDataArr = [BeautyPictureModel modelHanderWithArray:result[@"data"]];
        // 将新的数据依次加到数据驻足里面
        if (self.number > self.tagid) {
            NSString *title = NSLocalizedString(@"提示", nil);
            NSString *message = NSLocalizedString(@"没有图片可以观看了,😇", nil);
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
            [self presentViewController:alert animated:YES completion:^{
            }];
            [self performSelector:@selector(ss:) withObject:alert afterDelay:3];
            NSLog(@"111");

        }
        else{
        for (NSInteger i = 0; i < 10; i++) {
            [_dataArr addObject:newDataArr[i]];
        }
//        if (_dataArr.count != 0) {
//            [self.view bringSubviewToFront:self.collectionview];
//        }
        // 刷新collectionView
        [self.collectionview reloadData];
        }
    }];
    [self.collectionview.mj_footer endRefreshing];
    self.number += 1;
    
}
#pragma mark - 数据处理
-(void)Handler
{
    NSString *str = @"http://appapi.17house.com/xiaoguotuApi.php?action=imageList&bid=6&page=1&pageSize=10&tagid=7";
    [AFNetworking GETWithURL:str completion:^(id result) {
        NSMutableArray *arr = result[@"data"];
        self.dataArr = [BeautyPictureModel modelHanderWithArray:arr];
        [_collectionview reloadData];
    }];
    [self.collectionview.mj_header endRefreshing];
}

#pragma mark - /// 创建视图
- (void)createSubviews{
    // 创建collectionView
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake((self.view.frame.size.width - 30) / 2, (self.view.frame.size.width - 30) / 2);
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 0, 10);
    self.collectionview = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) collectionViewLayout:layout];
    self.collectionview.delegate = self;
    self.collectionview.dataSource = self;
    
    // 判断当前是什么模式
    BOOL model = [AccountManager sharedInstance].isNight;
    if (model == YES) {
        self.collectionview.backgroundColor = [UIColor changeColorWithString:@"#a1a3a6"];
        
    } else {
        self.collectionview.backgroundColor = [UIColor clearColor];
        
    }
    [_collectionview registerClass:[BeautyPictureCell class] forCellWithReuseIdentifier:@"cell"];
    [self.view addSubview:_collectionview];
}
#pragma mark - cell个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _dataArr.count;
}
#pragma mark - 设置cell样式
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    BeautyPictureCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    
    
    if (_dataArr.count != 0) {
        BeautyPictureModel *m = _dataArr[indexPath.row];
        [cell.imgview sd_setImageWithURL:[NSURL URLWithString:m.url] placeholderImage:[UIImage imageNamed:@"fang"]];
         UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(show:)];
        [cell.imgview addGestureRecognizer:tap];
        cell.imgview.userInteractionEnabled = YES;//用户交互
    }
    return cell;
}
#pragma mark - 点击变大图片
- (void)show:(UITapGestureRecognizer *)tap
{
    if (![(UIImageView *)tap.view image]) {
        return;
    }
    //scrollView作为背景
    UIScrollView *bgView = [[UIScrollView alloc] init];
    bgView.frame = [UIScreen mainScreen].bounds;
    bgView.backgroundColor = [UIColor blackColor];//背景颜色
    //背景手势
    UITapGestureRecognizer *tapBg = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBgView:)];
    //添加手势到scrollView上
    [bgView addGestureRecognizer:tapBg];
    //图片
    UIImageView *picView = (UIImageView *)tap.view;
    
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.image = picView.image;
    imageView.frame = [bgView convertRect:picView.frame fromView:self.view];
    [bgView addSubview:imageView];
    
    [[[UIApplication sharedApplication] keyWindow] addSubview:bgView];
    
    self.imageview = imageView;
    self.originalFrame = imageView.frame;
    self.scrollView = bgView;
    //最大放大比例
    self.scrollView.maximumZoomScale = 1.5;
    self.scrollView.delegate = self;
    
    [UIView animateWithDuration:0.5 animations:^{
        CGRect frame = imageView.frame;
        frame.size.width = bgView.frame.size.width;
        frame.size.height = frame.size.width * (imageView.image.size.height / imageView.image.size.width);
        frame.origin.x = 0;
        frame.origin.y = (bgView.frame.size.height - frame.size.height) * 0.5;
        imageView.frame = frame;
    }];
}
-(void)tapBgView:(UITapGestureRecognizer *)tapBgRecognizer{
    self.scrollView.contentOffset = CGPointZero;
    [UIView animateWithDuration:0.5 animations:^{
        self.imageview.frame = self.originalFrame;
        tapBgRecognizer.view.backgroundColor = [UIColor clearColor];
    } completion:^(BOOL finished) {
        [tapBgRecognizer.view removeFromSuperview];
        self.scrollView = nil;
        self.imageview = nil;
    }];
}
- (void)ss:(UIAlertController *)a
{
    [a dismissViewControllerAnimated:YES completion:nil];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
